package starter

import (
	"net/http"

	"cashway.com/cis/assistant/controller"
	"cashway.com/cis/assistant/middleware"
	"cashway.com/cis/assistant/types"
)

// 注册路由，并统一添加日志，不使用请求体解析中间件
func AddCommonRoute[T any](pattern string, handle types.HandleFunc[T]) {
	AddRouteAndUseMiddlewares[T](pattern, handle, []types.MiddlewareFunc[T]{
		middleware.UseLogger[T],
	})
}

// 注册路由，并统一添加日志，使用请求体解析中间件
func AddParseBodyCommonRoute[T any](pattern string, handle types.HandleFunc[T]) {
	AddRouteAndUseMiddlewares[T](pattern, handle, []types.MiddlewareFunc[T]{
		middleware.UseLogger[T],
		middleware.UseBodyParser[T],
	})
}

// 注册异步处理路由，并统一添加日志，使用请求体解析中间件
func AddAsyncParseBodyCommonRoute[T any](pattern string, handle types.HandleFunc[T]) {
	AddRouteAndUseMiddlewares[T](pattern, handle, []types.MiddlewareFunc[T]{
		middleware.UseAsync[T],
		middleware.UseLogger[T],
		middleware.UseBodyParser[T],
	})
}

// 注册路由并使用中间件
func AddRouteAndUseMiddlewares[T any](pattern string, handle types.HandleFunc[T], useMiddlewareFuncList []types.MiddlewareFunc[T]) {
	last := handle
	// 先注册的后执行
	for _, useMiddlewareFunc := range useMiddlewareFuncList {
		last = useMiddlewareFunc(last)
	}
	http.HandleFunc(pattern, func(resp http.ResponseWriter, req *http.Request) {
		last(&types.ResponseWriter{ResponseWriter: resp}, &types.Request[T]{Request: *req})
	})
}

func init() {
	AddCommonRoute("/wellcome", controller.Wellcome)
	AddParseBodyCommonRoute("/tcpRequest", controller.TcpRequest)
	AddAsyncParseBodyCommonRoute("/tcpRequest/async", controller.TcpRequest)
	AddParseBodyCommonRoute("/uploadFileToRemote", controller.UploadFileToRemote)
	AddAsyncParseBodyCommonRoute("/uploadFileToRemote/async", controller.UploadFileToRemote)
	AddParseBodyCommonRoute("/compress", controller.Compress)
	AddAsyncParseBodyCommonRoute("/compress/async", controller.Compress)
	AddParseBodyCommonRoute("/decompress", controller.Decompress)
	AddAsyncParseBodyCommonRoute("/decompress/async", controller.Decompress)
	AddParseBodyCommonRoute("/sftpUploadFileToRemote", controller.SftpUploadFileToRemote)
	AddAsyncParseBodyCommonRoute("/sftpUploadFileToRemote/async", controller.SftpUploadFileToRemote)
}
